package cn.bird.storm.validated.paramcheck;


import cn.bird.exception.BusiException;
import cn.bird.storm.validated.paramcheck.inter.ICheckBean;
import cn.bird.storm.validated.paramcheck.inter.ICheckModel;
import cn.bird.storm.validated.paramcheck.model.customize.CustomizeTrait;
import cn.bird.storm.validated.paramcheck.model.least.LeastOneNotEmptyTrait;
import cn.bird.storm.validated.paramcheck.model.notempty.NotEmptyTrait;
import cn.bird.storm.validated.paramcheck.model.stringscope.StringScopeTrait;
import cn.bird.storm.validated.paramcheck.tool.CheckNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;

/**
 * 添加更多检验逻辑，需要分别实现{@link ICheckBean} 和 {@link ICheckModel}添加对用的trait即可
 * 然后，参照本类中{@link #notEmpty(String, Object)} 实现即可
 */
@Slf4j
public class ParameterCheckBuilder implements
        NotEmptyTrait, LeastOneNotEmptyTrait, CustomizeTrait, StringScopeTrait {

    protected ParameterCheckBuilder(){
    }
    /**
     * 最终方法，进行检验
     */
    protected void check(){
        CheckNode checkNode = Optional.ofNullable(ParamCheckComponent.getCheckNode())
                .orElseThrow(() -> new BusiException("参数校验未知错误"));
        Map<String, ICheckModel> checkModelMap = checkNode.getModelMap();
        if (CollUtil.isEmpty(checkModelMap)) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        checkModelMap.values()
                .forEach(iCheckModel -> sb.append(iCheckModel.check()));
        if (StrUtil.isBlank(sb)) {
            log.info("参数校验通过！");
            return;
        }
        String result = sb.toString().trim();
        log.info("参数校验工具结果为：{}{}", System.lineSeparator(), result);
        throw new BusiException(result);
    }

}
